package com.huawei;


import com.huawei.games.ComputerControl;
import com.huawei.games.impl.ComputerControlImpl;
import com.huawei.memory.SingletonMemory;
import com.huawei.gamerun.RockPaperScissorsThread;
import com.huawei.result.Result;
import lombok.extern.slf4j.Slf4j;
import com.huawei.users.Machine;

import java.util.Arrays;
import java.util.concurrent.*;

/**
 * @program: playgame
 * @Description:
 * @author: crr
 * @date: 2022/4/20
 */
@Slf4j
public class PlayGames {
    public static void main(String[] args) {

        //计数次数
        final int count = 2;
        //创建CountDownLatch 实例  预定计数次数:10
        final CountDownLatch latch = new CountDownLatch(count);

        ComputerControl operation = new ComputerControlImpl();
        /** Integer[] Arr = Arrays.stream(arr).boxed().toArray(Integer[]::new); **/
        Integer[] personResult = Arrays.stream(operation.computerRandomGenerate(5)).boxed().toArray(Integer[]::new);
        Machine person = new Machine("tom",personResult);

        Integer[] computerResult = Arrays.stream(operation.computerRandomGenerate(5)).boxed().toArray(Integer[]::new);
        Machine machine = new Machine("computer1",computerResult);

        RockPaperScissorsThread game = new RockPaperScissorsThread(person, machine,latch);

        Integer[] personResult1 = Arrays.stream(operation.computerRandomGenerate(5)).boxed().toArray(Integer[]::new);
        Machine person1 = new Machine("tom1",personResult1);

        Integer[] computerResult1 = Arrays.stream(operation.computerRandomGenerate(5)).boxed().toArray(Integer[]::new);
        Machine machine1 = new Machine("computer1",computerResult1);

        RockPaperScissorsThread game1 = new RockPaperScissorsThread(person, machine,latch);

        //使用线程池
        ExecutorService threadPool = new ThreadPoolExecutor(
                2,
                5,
                10,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue(3),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.DiscardPolicy());

        threadPool.execute(game);
        threadPool.execute(game1);

        try {
            //线程countDown()都执行之后才会释放当前线程,程序才能继续往后执行
            latch.await();
        } catch (InterruptedException e) {
            log.error("error in latch",e);
        }
        for(Result result : SingletonMemory.getSingleton().getResultList()){
            System.out.println(result);
        }

    }
}
